package com.like.miaosha.controller;

import com.like.miaosha.access.AccessLimit;
import com.like.miaosha.domain.MiaoshaOrder;
import com.like.miaosha.domain.MiaoshaUser;

import com.like.miaosha.domain.OrderInfo;
import com.like.miaosha.rebbitmq.MQSender;
import com.like.miaosha.rebbitmq.MiaoshaMessage;
import com.like.miaosha.redis.AccessKey;
import com.like.miaosha.redis.GoodsKey;
import com.like.miaosha.redis.MiaoshaKey;
import com.like.miaosha.redis.RedisService;
import com.like.miaosha.result.CodeMsg;
import com.like.miaosha.result.Result;
import com.like.miaosha.service.GoodsService;
import com.like.miaosha.service.MiaoshaService;
import com.like.miaosha.service.MiaoshaUserService;
import com.like.miaosha.service.OrderService;
import com.like.miaosha.util.MD5Util;
import com.like.miaosha.util.UUIDUtil;
import com.like.miaosha.vo.GoodsVo;
import com.sun.org.apache.xpath.internal.operations.Mod;
import javafx.scene.shape.VLineTo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.nio.file.attribute.AclEntryPermission;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/miaosha")
public class MiaoshaController implements InitializingBean {
    @Autowired
    MiaoshaUserService miaoshaUserService;

    @Autowired
    RedisService redisService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    MiaoshaService miaoshaService;

    @Autowired
    MQSender mqSender;

    private Map<Long, Boolean> localOverMap = new HashMap<>();

    /*
     *@author dongfengke
     *@Description 系统初始化
     *@Date 10:19 下午 2022/1/17
     *@Param
     *@Return
     **/
    @Override
    public void afterPropertiesSet() throws Exception {
        List<GoodsVo> goodsVos = goodsService.listGoodsVo();
        if (goodsVos == null) return;
        for (GoodsVo goodsVo : goodsVos) {
            redisService.set(GoodsKey.getMiaoshaGoodsStock, "" + goodsVo.getId(), goodsVo.getStockCount());
            localOverMap.put(goodsVo.getId(), false);
        }
    }

    @RequestMapping(value = "/{path}/do_miaosha", method = RequestMethod.POST)
    @ResponseBody
    public Result<Integer> toList(Model model, MiaoshaUser user,
                                  @RequestParam("goodsId") long goodsId,
                                  @PathVariable("path") String path) {


        if (user == null) return Result.error(CodeMsg.SESSION_ERROR);
        model.addAttribute("user", user);

        boolean check=miaoshaService.checkPath(user,goodsId,path);
        if(!check){
            return Result.error(CodeMsg.REQUEST_ILLEGAL);
        }

        boolean over = localOverMap.get(goodsId);
        if (over) return Result.error(CodeMsg.MIAOSHA_OVER);

        Long stock = redisService.decr(GoodsKey.getMiaoshaGoodsStock, "" + goodsId);
        if (stock < 0) {
            localOverMap.put(goodsId, true);
            return Result.error(CodeMsg.MIAOSHA_OVER);
        }
        //判断是否已经秒杀到了
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(), goodsId);
        if (order != null) {
            return Result.error(CodeMsg.REPEAT_MIAOSHA);
        }
        //入队
        MiaoshaMessage miaoshaMessage = new MiaoshaMessage();
        miaoshaMessage.setMiaoshaUser(user);
        miaoshaMessage.setGoodsId(goodsId);
        mqSender.sendMiaoshaMessage(miaoshaMessage);

        return Result.success(0);

//        GoodsVo goods=goodsService.getGoodsVoByGoodsId(goodsId);
//        //判断库存
//        Integer stockCount = goods.getStockCount();
//        if(stockCount<=0){
//            return Result.error(CodeMsg.MIAOSHA_OVER);
//        }
//        //判断是否已经秒杀到
//
//        MiaoshaOrder order= orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(),goodsId);
//        if(order!=null){
//            return Result.error(CodeMsg.REPEAT_MIAOSHA);
//        }
//        OrderInfo orderInfo=miaoshaService.miaosha(user,goods);
//
//        System.out.println(goods.getStockCount());
//        return Result.success(orderInfo);

    }

    /*
     *@author dongfengke
     *@Description order: 成功  -1：秒杀失败   0： 排队中
     *@Date 11:19 下午 2022/1/17
     *@Param
     *@Return
     **/
    @RequestMapping(value = "/result", method = RequestMethod.GET)
    @ResponseBody
    public Result<Long> miaoshaResult(Model model, MiaoshaUser user, @RequestParam("goodsId") long goodsId) {
        model.addAttribute("user", user);
        if (user == null) return Result.error(CodeMsg.SESSION_ERROR);
        long result = miaoshaService.getMiaoshaResult(user.getId(), goodsId);
        return Result.success(result);
    }

    @AccessLimit(seconds = 5,maxCount = 5,needLogin = true)
    @RequestMapping(value = "/path", method = RequestMethod.GET)
    @ResponseBody
    public Result<String> getMiaoshaPath(Model model, MiaoshaUser user, HttpServletRequest req,
                                         @RequestParam("goodsId") long goodsId,
                                         @RequestParam(value = "verifyCode",defaultValue = "0") int verifyCode) {
        if (user == null) return Result.error(CodeMsg.SESSION_ERROR);

        //查询访问次数
        model.addAttribute("user", user);
        boolean check=miaoshaService.checkVerifyCode(user,goodsId,verifyCode);
        if(!check)
            return Result.error(CodeMsg.REQUEST_ILLEGAL);
        String path=miaoshaService.createMiaoshaPath(user,goodsId);
        return Result.success(path);
    }

    @RequestMapping(value="/verifyCode",method = RequestMethod.GET)
    @ResponseBody
    public Result<String> getMiaoshaVerifyCode(HttpServletResponse resp,MiaoshaUser user,
                                               @RequestParam("goodsId") long goodsId){
        if(user==null) return Result.error(CodeMsg.SESSION_ERROR);
        try{
            BufferedImage image=miaoshaService.createVerifyCode(user,goodsId);
            OutputStream out =resp.getOutputStream();
            ImageIO.write(image,"JPEG",out);
            out.flush();
            out.close();
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(CodeMsg.MIAOSHA_FAIL);
        }
    }
}
